﻿using Common.Logging;
using Quartz;
using RestSharp;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

namespace CdhpyScheduler.Core
{
    public class HttpJob : IJob
    {
        public static Action<string> Log = (content) => { Console.WriteLine(content); };

        public void Execute(IJobExecutionContext context)
        {
            string guid = Guid.NewGuid().ToString().Substring(0, 6);
            JobKey key = context.JobDetail.Key;
            JobDataMap dataMap = context.JobDetail.JobDataMap;

            string url = dataMap.GetString("url");
            var verbStr = dataMap.GetString("httpMethod");
            string jobKey = context.JobDetail.Key.Name;
            DateTime nextTriggerTime = context.Trigger.GetNextFireTimeUtc().HasValue ?
                context.Trigger.GetNextFireTimeUtc().Value.AddHours(8).DateTime : default(DateTime);
            //DateTime triggerTime = context.Trigger.StartTimeUtc.AddHours(8).DateTime;
            //DateTime actualFireTime = context.ScheduledFireTimeUtc.Value.AddHours(8).DateTime;


            Log($"[{guid}] Ready to fire job '{jobKey}' : {url}");

            Method method = Method.GET;
            switch (verbStr?.ToUpper())
            {
                case "GET": method = Method.GET; break;
                case "POST": method = Method.POST; break;
                case "PUT": method = Method.PUT; break;
                case "DELETE": method = Method.DELETE; break;
            }

            var client = new RestClient(url);
            var request = new RestRequest(method);
            var response = client.Execute(request);
            var rspContent = response.Content;

            Log($"[{guid}] Job finished: {(int)response.StatusCode}({response.StatusCode}), response:{response.Content}, exception:{response.ErrorMessage ?? String.Concat("无")}");
            if (nextTriggerTime != default(DateTime))
            {
                Log($"[{guid}] Next fire time: {nextTriggerTime.ToString("yyyy-MM-dd HH:mm:ss")}");
            }
            else
            {
                Log($"[{guid}] Job END.");
            }
        }
    }
}
